# -*- coding: utf-8 -*-

import smtplib
import os
import sys
import traceback
from email.mime.text import MIMEText
from email.mime.multipart import  MIMEMultipart
from email.mime.application import MIMEApplication

class EmailSender(object):
    def __init__(self):
         self.host = '192.168.1.21'
         self.port = 25
         self.pswd = '12345678A'
         self.sender = 'jiracollect@kaidi.com'
         self.platform = sys.platform
         self.iswin = False if "win" not in str(self.platform) else True

         self.LoginMail()

    def LoginMail(self):
        try:
            self.SmtpClient = smtplib.SMTP(self.host, self.port)
            self.Loginer = self.SmtpClient.login(self.sender, self.pswd)

            print("Login success : Loginer=", self.Loginer)  # loginRes =  (235, b'Authentication successful')
        except Exception as e:
            traceback.print_exc()
            print("Login mail account failed, err :", e)
    
    def SendMail(self, maillist, subject, body = None, files = []):
        msg= MIMEMultipart()
        msg.attach(MIMEText(body, 'plain', 'utf-8'))
        msg["From"] = self.sender

        if len(maillist)>1:
            msg['To'] = ','.join(maillist)
        else:
            msg['To'] = maillist[0]
        
        msg["Subject"] = subject
        for file in files:
            if os.path.exists(str(file)):
                filespart = MIMEApplication(open(file,'rb').read())
                if self.iswin:
                    file_name = file.split("\\")[-1]
                else:
                    print("sender at ubuntu sys ...")
                    file_name = file.split("/")[-1]
    
                print("file_name = ", file_name)
    
                filespart.add_header("Content-Disposition","attachment",filename=file_name)
                msg.attach(filespart)
            else:
                print('Current loading attachment \'{0}\' is not exist, Ingore it~'.format(file))
                continue
    
        try:
            if self.Loginer[0] == 235:
                self.SmtpClient.sendmail(self.sender, maillist, msg.as_string())
                print("mail has been send successfully~")
            else:
                print("send mail fail e --> code=", self.Loginer[0])
        except Exception as e:
            traceback.print_exc()
            print("send mail fail e --> ", e)

    def QuitMail(self):
        self.SmtpClient.quit()